package com.tfswx.jcyw.ruleenginedesigner.validation;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.nio.charset.StandardCharsets;

/**
 * @author ricky
 * @date 2021/11/30
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MaxLength.LengthValidator.class)
public @interface MaxLength {
    int value();

    String message() default "数值长度不正确";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};


    class LengthValidator implements ConstraintValidator<MaxLength, Object> {
        private int value;

        @Override
        public void initialize(MaxLength constraintAnnotation) {
            value = constraintAnnotation.value();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            if (value == null) {
                return true;
            }
            String s = value.toString();
            int length = s.getBytes(StandardCharsets.UTF_8).length;
            return length <= this.value;
        }
    }
}
